package com.controller;

import com.entity.ResponseEntity;
import com.entity.User;
import com.github.pagehelper.PageInfo;
import com.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/UserController")
public class UserController {
    @Autowired
    private HttpSession session;
    @Autowired
    private UserService userService;

    @PostMapping("/Users")
    public ResponseEntity addOne(@RequestBody @Valid User user){
        System.out.println("user = " + user);
        return userService.addOne(user);
    }

    @GetMapping( "/Users/pages/{pageNum}")
    public ResponseEntity findAll(@PathVariable int pageNum, HttpServletRequest request, HttpServletResponse response){
        ResponseEntity entity = userService.findAll(pageNum);
        PageInfo pageInfo = new PageInfo((List)entity.getData());
        entity.setData(pageInfo);
        return entity;
    }

    @GetMapping("/Users/{username}")
    public ResponseEntity checkRepeatName(@PathVariable String username){
        return userService.findName(username);
    }

    @PostMapping("/Users/login")
    public ResponseEntity login(@RequestBody @Valid User user){
        System.out.println("user = " + user);
        ResponseEntity entity = userService.findOne(user);
        if(entity.getCode() == 200){
            session.setAttribute("user",(User)entity.getData());
            System.out.println("成功登录");
        }
        return entity;
    }
}
